package com.gm.wholesale.module.settlement.ui.detail;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment;
import com.gm.commonlib.interfaces.IResultListener;
import com.gm.commonlib.module.evenbus.EventMessage;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.InputDialog;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.superview.SuperTextView;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.module.evenbus.EvenBusUtil;
import com.gm.wholesale.module.evenbus.EventBusType;
import com.gm.wholesale.module.order.view.PayMoneyView;
import com.gm.wholesale.module.order.view.RefundMoneyView;
import com.gm.wholesale.module.settlement.bean.CustomerSettlementBean;
import com.gm.wholesale.module.settlement.bean.CustomerSettlementDetail;
import com.gm.wholesale.module.settlement.model.ReconciliationMode;
import com.gm.wholesale.module.settlement.ui.tab.TabType;
import com.gm.wholesale.util.ViewUtil;

import java.util.HashMap;
import java.util.List;

public class SettlementDetailFragment extends BaseFragment {
    private ImageView backImage;
    private TextView titleTv;
    private ImageView updateTitleImage;
    private SuperTextView cancleBtn;
    private SuperTextView shareBtn;
    private SuperTextView payBtn;

    private ListView mListView;

    private TextView totalTv;
    private TextView detailPriceTv;
    private int mType;
    private CustomerSettlementDetail mDetail;
    private CustomerSettlementBean customerSettlementBean;

    public static void showUI(int type, CustomerSettlementBean data, FragmentActivity activity) {
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        SettlementDetailFragment fragment = new SettlementDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putSerializable("data", data);
        fragment.setArguments(bundle);
        transaction.add(R.id.mainView, fragment);
        transaction.commitAllowingStateLoss();


    }


    @Override
    public void onCreateViewFinish() {
        getOrderDetail();
    }

    private void finishUI() {
        ViewUtil.backFragment(getActivity());
        ViewUtil.finishFragment(getActivity(), this);
    }

    @Override
    public void onReceiveEvent(EventMessage event) {
        if (event.getCode() == EventBusType.FINISH_SETTLEMENT_DETAIL.getType()) {
            finishUI();
        }

    }

    @Override
    protected void onCreateContentBody(ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.fragment_dz_detail, parent);
        initView(view);
        mType = getArguments().getInt("type");
        customerSettlementBean = (CustomerSettlementBean) getArguments().getSerializable("data");
        payBtn.setOnClickListener(v -> {
            if (RepeatClickUtils.check()) {
                return;
            }
            showPayMoneyView();
        });

        switch (mType) {
            case TabType.WAITE_TO_PAY:
                shareBtn.setVisibility(View.VISIBLE);
                cancleBtn.setVisibility(View.VISIBLE);
                payBtn.setVisibility(View.VISIBLE);
                payBtn.setCenterString("标记支付");
                break;
            case TabType.WAITE_TO_SETTLEMENT:
                shareBtn.setVisibility(View.VISIBLE);
                payBtn.setCenterString("继续支付");
                payBtn.setVisibility(View.VISIBLE);
                break;
            case TabType.FINISH_DZ:
                shareBtn.setVisibility(View.VISIBLE);
                break;
        }


    }

    private void showBaseInfo() {
        double totalPrice = mDetail.getTotalAmount();
        if (totalPrice <= 0) {
            totalPrice = mDetail.getShouldPayAmount();
        }
        totalTv.setText("合计:" + NumberUtils.getMoneyWithUnitStrig(totalPrice));
        titleTv.setText(mDetail.getName());
        int status = mDetail.getStatus();
        //1 待结算 2已付款未结算 3已结算
        switch (status) {
            case 1:
                shareBtn.setVisibility(View.VISIBLE);
                cancleBtn.setVisibility(View.VISIBLE);
                payBtn.setVisibility(View.VISIBLE);
                payBtn.setCenterString("标记支付");
                break;
            case 2:
                shareBtn.setVisibility(View.VISIBLE);
                payBtn.setCenterString("继续支付");
                payBtn.setVisibility(View.VISIBLE);
                String detail1 = "(优惠: " + NumberUtils.getMoneyWithUnitStrig(mDetail.getDiscountAmount())
                        + "  |   实结金额:" + NumberUtils.getMoneyWithUnitStrig(mDetail.getPaidAmount())
                        + "  |   待结金额:" + NumberUtils.getMoneyWithUnitStrig(mDetail.getBalanceAmount()) + ")";
                SpannableStringBuilder builder = new SpannableStringBuilder(detail1);
                ForegroundColorSpan colorSpan = new ForegroundColorSpan(getResources().getColor(R.color.color_FE5000));
                int start = detail1.indexOf("待");
                builder.setSpan(colorSpan, start, detail1.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                detailPriceTv.setText(builder);

                detailPriceTv.setVisibility(View.VISIBLE);
                break;
            case 3:
                shareBtn.setVisibility(View.VISIBLE);
                payBtn.setVisibility(View.GONE);
                String detail = "(优惠: " + NumberUtils.getMoneyWithUnitStrig(mDetail.getDiscountAmount())
                        + "  |   实收:" + NumberUtils.getMoneyWithUnitStrig(mDetail.getPaidAmount()) + ")";
                detailPriceTv.setText(detail);
                detailPriceTv.setVisibility(View.VISIBLE);
                break;
        }

    }


    private void showPayMoneyView() {
        if (mDetail == null) return;

        customerSettlementBean.setTotalAmount(mDetail.getTotalAmount());
        customerSettlementBean.setShouldPayAmount(mDetail.getShouldPayAmount());
        customerSettlementBean.setPaidAmount(mDetail.getPaidAmount());
        customerSettlementBean.setBalanceAmount(mDetail.getBalanceAmount());
        customerSettlementBean.setVersion(mDetail.getVersion());
        if (mType == 1) { //未支付进入
            if (mDetail.getShouldPayAmount() > 0) {//支付
                showPayView(PayMoneyView.PAY_TYPE_UNPAY, customerSettlementBean);
            } else { //退款
                showRefundMoneyView(PayMoneyView.PAY_TYPE_UNPAY, customerSettlementBean);
            }
        } else {
            if (mDetail.getBalanceAmount() > 0) {
                showPayView(PayMoneyView.PAY_TYPE_PARTIAL_PAYMENT, customerSettlementBean);
            } else {
                showRefundMoneyView(PayMoneyView.PAY_TYPE_PARTIAL_PAYMENT, customerSettlementBean);
            }

        }


    }

    private void showPayView(int type, CustomerSettlementBean customerSettlementBean) {
        PayMoneyView payMoneyView = new PayMoneyView(getActivity());
        payMoneyView.showPayMoney(type, customerSettlementBean);
        payMoneyView.setOnSubmitClickListener((payInfoBean, goodBeans) -> {
            HashMap<String, Object> data = new HashMap<>();
            data.put("payMent", payInfoBean.getPayment());
            data.put("payAmount", Double.parseDouble(payInfoBean.getPaidAmount()));
            data.put("discountAmount", Double.parseDouble(payInfoBean.getDiscountAmount()));
            data.put("version", mDetail.getVersion());
            ReconciliationMode.payOrder((IBaseView) getActivity(), customerSettlementBean.getId(), data, new BaseHttpObserver<BaseResp>() {
                @Override
                protected void handleResultOkResp(BaseResp resp) {
                    payResult();
                }
            });

        });
        Popupwindow.showPopCenterView(getActivity(), payMoneyView);
    }


    private void showRefundMoneyView(int type, CustomerSettlementBean customerSettlementBean) {
        RefundMoneyView refundMoneyView = new RefundMoneyView(getActivity());
        refundMoneyView.showView(type, customerSettlementBean, new IResultListener<Boolean>() {
            @Override
            public void onResult(Boolean result) {
                payResult();
            }
        });
        Popupwindow.showPopCenterView(getActivity(), refundMoneyView);

    }

    private void payResult() {
        Popupwindow.hiddenPop();
        ToastUtil.showToast("支付成功");
        getOrderDetail();
        //更新待结算
        EvenBusUtil.updateSettlemenList();
        //更新未支付
        EvenBusUtil.updatePayTabList();
    }


    private void getOrderDetail() {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        // queryData.put("status", mType);
        queryData.put("customerSettlementIds", customerSettlementBean.getId());
        queryData.put("isReturnDetail", 1);
        ReconciliationMode.getOrderDetail((IBaseView) getActivity(), queryData, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(BasePageData<CustomerSettlementDetail> resp) {
                if (resp != null && resp.getData() != null && resp.getData().getDatas() != null
                        && !resp.getData().getDatas().isEmpty()) {
                    mDetail = resp.getData().getDatas().get(0);
                    showBaseInfo();
                    updateView(resp.getData().getDatas().get(0).getCustomerSettlementDetails());
                }
            }
        });
    }

    private void updateView(List<CustomerSettlementDetail.CustomerSettlementDetailsBean> mDatas) {
        if (mDatas != null) {
            mListView.setAdapter(new CommonAdapter<>(getActivity(), mDatas, R.layout.view_list_dz_item) {
                @Override
                public void convert(ViewHolder viewHolder, final CustomerSettlementDetail.CustomerSettlementDetailsBean data) {
                    viewHolder.setText(R.id.nameTv, data.getCustomerName());
                    viewHolder.setText(R.id.createTimeTv, data.getCreateTime());
                    viewHolder.setText(R.id.numberTv, data.getNo());
                    TextView ntTv = viewHolder.getView(R.id.ntTv);
                    int status = data.getStatus();
                    int type = data.getType();
                    ntTv.setVisibility(View.GONE);
                    //1为订单，2为售后单
                    if (type == 2) {
                        ntTv.setText("退");
                        ntTv.setVisibility(View.VISIBLE);
                    } else {
                        //1.未对账，2.对账中，3结算完成
                        if (status != 3) {
                            ntTv.setVisibility(View.VISIBLE);
                            ntTv.setText("欠");
                        }
                    }
                    viewHolder.setText(R.id.priceTv, NumberUtils.getMoneyWithUnitStrig(data.getAmount()));
                }
            });
        }
    }


    private void initView(View view) {
        mListView = view.findViewById(R.id.listView);
        backImage = view.findViewById(R.id.backImage);
        titleTv = view.findViewById(R.id.titleTv);
        updateTitleImage = view.findViewById(R.id.updateTitleImage);
        cancleBtn = view.findViewById(R.id.cancleBtn);
        shareBtn = view.findViewById(R.id.shareBtn);
        payBtn = view.findViewById(R.id.payBtn);
        totalTv = view.findViewById(R.id.totalTv);
        detailPriceTv = view.findViewById(R.id.detailPriceTv);
        backImage.setOnClickListener(v -> finishUI());
        updateTitleImage.setOnClickListener(v -> updateOrderName());

        cancleBtn.setOnClickListener(v -> {
            if (mDetail == null) return;
            ReconciliationMode.cancelSettlement((IBaseView) getActivity(), mDetail.getId(), new BaseHttpObserver<BaseResp>() {
                @Override
                protected void handleResultOkResp(BaseResp resp) {
                    ToastUtil.showToast("取消成功");
                    EvenBusUtil.cancelDZOrder();
                    finishUI();
                }
            });
        });
    }

    private void updateOrderName() {
        if (mDetail == null) return;
        InputDialog dialog = DialogUtil.showInputDialog(getActivity(), "修改对账单名字", mDetail.getName(), (inputData, inputDialog) -> {
            if (TextUtils.isEmpty(inputData)) {
                ToastUtil.showToast("对账单名字不能为空");
                return;
            }
            ReconciliationMode.updateOrderName((IBaseView) getActivity(), mDetail.getId(), inputData, new BaseHttpObserver<>() {
                @Override
                protected void handleResultOkResp(BaseResp resp) {
                    inputDialog.dismiss();
                    ToastUtil.showToast("修改成功");
                    mDetail.setName(inputData);
                    showBaseInfo();
                    EvenBusUtil.updateWaittoAccuntList();

                }
            });
        });
        dialog.setEdInputFilter(new InputFilter[]{new InputFilter.LengthFilter(20)});
    }
}
